import 'package:flutter/material.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/book/BookSearchDto.dart';
import 'package:ichinesereader/models/common/LevelOption.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/addons/quickSearchBooks.dart';

class LevelChioceChipWidget extends StatefulWidget {
  LevelChioceChipWidget({Key? key}) : super(key: key);

  @override
  State<LevelChioceChipWidget> createState() => _LevelChioceChipWidgetState();
}

class _LevelChioceChipWidgetState extends State<LevelChioceChipWidget> {
  var box = Hive.box('appconfig');
  var levelOptions = Constants.levelOptions;
  int selectedLevelOption = 99;
  bool hasLevelSelected = false;

  @override
  Widget build(BuildContext context) {
    Log.debug('build LevelChioceChipWidget');
    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    bool isAdmin = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_SchoolAdmin;
    if (isTeacher || isAdmin) {
      levelOptions.removeWhere((element) {
        // var item = element as LevelOption;
        return element.value.toString() == 'pre';
      });
    }
    final BooksController _booksController = Get.find();

    return Container(
      height: 45.0,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: Constants.levelOptions.length,
        itemBuilder: ((context, index) {
          return Padding(
            padding: const EdgeInsets.symmetric(
              horizontal: 3.0,
            ),
            child: ChoiceChip(
              padding: EdgeInsets.symmetric(horizontal: 8.0),
              shape: BeveledRectangleBorder(
                side: BorderSide(color: Colors.white, width: 0.3),
                borderRadius: BorderRadius.circular(1.0),
              ),
              backgroundColor: hexStringToHexInt(
                Constants.levelOptions[index].color.toString(),
              ),
              label: Text(
                Constants.levelOptions[index].label
                    .toString()
                    .replaceAll('Level 0', 'N/A')
                    .replaceAll('Level ', ''),
                style:
                    TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
              ),
              selectedColor: Colors.black,
              selected: selectedLevelOption == index,
              onSelected: (selected) {
                setState(() {
                  if (selected ==false &&  selectedLevelOption == index) {
                    hasLevelSelected = selected;
                    selectedLevelOption = 99;
                  }else
                  {
                    selectedLevelOption = index;
                    hasLevelSelected = selected;
                  }
                });

                if (Constants.levelOptions[index].value.toString() == 'pre') {
                  Get.toNamed('/student/basicCardList');
                }
                BookSearchDto dto = new BookSearchDto();
                dto.proficiencyLevel = [];
                List<String> levelstr = [];
                List<LevelOption> levelOptions = [];

                if (hasLevelSelected) {
                  var item = Constants.levelOptions[index];
                  levelstr.add(item.value.toString());
                  if (item.value.toString() == 'pre') {
                    Get.toNamed('/student/basicCardList');
                  }
                  levelOptions.add(item);

                  _booksController.setBookSearchDto(dto);
                  _booksController.setLevelOptions(levelOptions);
                  if (levelstr.length > 0) {
                    dto.proficiencyLevel?.addAll(levelstr);

                    if (searchTextController.text.trim() != "" &&
                        searchTextController.text.length >= 2) {
                      dto.query = searchTextController.text;
                    }
                    _booksController.fetchSearchOpenLibraryBookItems(
                        Constants.pageLimit, 0, dto);
                  } else {
                    _booksController.fetchOpenReadingItems(
                        Constants.pageLimit, 0);
                  }
                } else {

                    if (searchTextController.text.trim() != "" &&
                        searchTextController.text.length >= 2) {
                      dto.query = searchTextController.text;
                    }

                   _booksController.setBookSearchDto(dto);
                  _booksController.setLevelOptions(levelOptions);

                  _booksController.fetchOpenReadingItems(
                      Constants.pageLimit, 0);
                }
              },
            ),
          );
        }),
      ),
    );
  }
}
